package com.yy.glide.recycle;

import android.graphics.Bitmap;
import android.util.LruCache;

import java.util.NavigableMap;
import java.util.TreeMap;

public class LruBitmapPool extends LruCache<Integer, Bitmap> implements BitmapPool {
    private NavigableMap<Integer, Integer> map = new TreeMap<>();
    private static final int MAX_OVER_SIZE = 2;
    private boolean isRemoved;

    public LruBitmapPool(int maxSize) {
        super(maxSize);
    }

    @Override
    protected int sizeOf(Integer key, Bitmap value) {
        return value.getAllocationByteCount();
    }

    @Override
    protected void entryRemoved(boolean evicted, Integer key, Bitmap oldValue, Bitmap newValue) {
        super.entryRemoved(evicted, key, oldValue, newValue);
        map.remove(key);
        if (!isRemoved) {
            oldValue.recycle();
        }
    }

    @Override
    public void put(Bitmap bitmap) {
        if (!bitmap.isMutable()) {
            bitmap.recycle();
            return;
        }

        int size = bitmap.getAllocationByteCount();
        if (size > maxSize()) {
            bitmap.recycle();
            return;
        }
        put(size, bitmap);
        map.put(size, 0);
    }

    @Override
    public Bitmap get(int width, int height, Bitmap.Config config) {
        int size = width * height * (config == Bitmap.Config.ARGB_8888 ? 4 : 2);
        //获取等于或者size的key
        Integer key = map.ceilingKey(size);
        if (key != null && key <= size * MAX_OVER_SIZE) {
            isRemoved = true;
            Bitmap bitmap = remove(key);
            isRemoved = false;
            return bitmap;
        }
        return null;
    }
}
